import router from "../router";
import api from "@/api";
import {getRequest} from "./requestUtil"
import store from '../store'
import navigation from '@/components/navigationBar/index.vue'

export function initMenu() {
    if (store.state.menuList.length > 0) {
        return
    }
    // 查询用户菜单
    getRequest(api.menu).then((data) => {
        if (data) {
            var menuList = data.data;
            let temp1 = menuList[0]
            menuList[0]={
                children:[temp1],
                path: "/",
                component: "SideBar"
            }
            menuList.forEach(item => {
                if (item.component == "SideBar"){
                    item.icon = "iconfont " + item.icon;
                    item.component = navigation
                }
                if (item.children && item.children.length > 0) {
                    item.children.forEach(route => {
                        route.icon = "iconfont " + route.icon;
                        route.component = formatComponent(route.component)
                    });
                }
            })
            store.commit("saveMenuList", menuList);
            router.addRoutes(menuList)
        }
    });
}

export const formatComponent = view => {
    return resolve => require(['@/views' + view], resolve);
};